package com.yixiu.study.juc.taobao.num1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @CalssName T03_LockSupport
 * @Description
 * @Author yixiu
 * @Date 2021/6/25 10:43
 * @Verison num1.0
 **/
public class T03_LockSupport {

    volatile List lists = new ArrayList();

    public void add(Object o){
        lists.add(o);
    }

    public int size(){
        return lists.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        T03_LockSupport c = new T03_LockSupport();

        t2 = new Thread(() -> {
            System.out.println("t2 启动");
            if(c.size() != 5){
                LockSupport.park();
            }
            System.out.println("t2 结束");
            LockSupport.unpark(t1);
        }, "t2");

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1 = new Thread(() -> {
            System.out.println("t1 启动");

            for (int i = 0; i < 10; i++) {
                c.add(new Object());
                System.out.println("add" + i);
                if(c.size() == 5){
                    LockSupport.unpark(t2);
                    LockSupport.park();
                }
            }
            System.out.println("t1 结束");
        }, "t1");

        //需要注意先启动线程t2再启动线程t1
        t2.start();
        t1.start();

    }


}
